package com.rivues.util.datasource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.alibaba.druid.pool.DruidDataSource;
import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.model.Database;
import com.rivues.util.service.cache.CacheHelper;
import com.rivues.util.tools.PropertiesTools;

public class JndiDataSource extends DruidDataSource{
	private javax.sql.DataSource jndiDataSource ;
	/**
	 * 
	 */
	private static final long serialVersionUID = 8286522203260959329L;
	
	public JndiDataSource(Database database){
		Context context;
		
		Object factory = CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("INITIAL_CONTEXT_FACTORY", database.getOrgi()) ;
		Object provider_url = CacheHelper.getDistributedDictionaryCacheBean().getCacheObject("PROVIDER_URL", database.getOrgi()) ;
		try {
			if(factory!=null&&factory.toString().length()>0&&provider_url!=null&&provider_url.toString().length()>0){
				Properties prop = null;  
				prop = new Properties();   
			    prop.put(Context.INITIAL_CONTEXT_FACTORY , factory.toString()); 
			    prop.put(Context.PROVIDER_URL , provider_url.toString());  
			    context = new InitialContext(prop);
			}else{
				context = new InitialContext();
				context = (Context)context.lookup("java:comp/env");
			}
			jndiDataSource = (javax.sql.DataSource)context.lookup(database.getJndiname()); 
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
    public Connection getConnection() throws SQLException {
        return jndiDataSource.getConnection();
    }
}
